<template>
  <div class="login">
    <div class="login-main">
      <div class="login-title">登录</div>
      <el-form
        ref="loginForm"
        :model="loginFormData"
        :rules="rules"
        label-width="70px"
        class="login-form"
        @submit.native.prevent
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginFormData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input
            type="password"
            autocomplete="off"
            v-model="loginFormData.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="submit" native-type="submit">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { userApi } from '../../api/user';
import { ElMessage } from 'element-plus';
export default {
  setup(props) {
    const router = useRouter();
    const loginForm = ref();
    const loginFormData = ref({
      username: '',
      password: '',
    });
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (loginFormData.password !== '') {
          loginForm.value.validateField('password');
        }
        callback();
      }
    };
    // 表单：校验规则
    const rules = ref({
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
      password: [{ validator: validatePass, trigger: 'blur' }],
    });
    // 登录
    const submit = () => {
      loginForm.value.validate(vaild => {
        if (vaild) {
          userApi.login(JSON.parse(JSON.stringify(loginFormData.value))).then(res => {
            if (res.status === 0) {
              localStorage.setItem('Token', res.data);
              // 登录校验通过
              router.push('/');
              ElMessage({
                message: res.msg,
                type: 'success',
              });
            }
          });
        }
      });
    };

    return {
      loginForm,
      loginFormData,
      rules,
      submit,
    };
  },
};
</script>

<style lang='scss' scoped>
.login {
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, #f9c2eb 0%, #a7c1ee 100%);
}
.login-main {
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 0 30px;
  width: 25%;
  min-width: 350px;
  height: 50%;
  min-height: 300px;
  background-color: #fff;
  border-radius: 20px;
  .login-title {
    padding-top: 40px;
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    line-height: 80px;
  }
  .login-form {
    margin-top: 40px;
    .el-button {
      width: 40%;
      margin-top: 30px;
    }
  }
}
</style>
